package com.weixing.mall.provider.util;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.HexUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.Mode;
import cn.hutool.crypto.Padding;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.AES;
import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
import org.apache.commons.codec.binary.Hex;

import javax.crypto.*;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

/**
 * @ClassName SecureUtil
 * @Description
 * @Author Small
 * @Date 2020/3/20 16:45
 * @Version 1.0
 **/
public class AuthCryptoUtil {


    /**
     * 用于生成随机iv
     *
     * @param length
     * @return
     * @throws NoSuchAlgorithmException
     */
    private static byte[] getSecureRandomIv(int length) throws NoSuchAlgorithmException {
        byte[] randomByte = new byte[length];
        SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
        secureRandom.nextBytes(randomByte);
        return randomByte;
    }

    private static byte[] getSecureKey(int size) {
        SecretKey secretKey = SecureUtil.generateKey(SymmetricAlgorithm.AES.getValue(), size);
        byte[] key = secretKey.getEncoded();
        return key;
    }

    public static String getSecureKeyStr(int size) {
        SecretKey secretKey = SecureUtil.generateKey(SymmetricAlgorithm.AES.getValue(), size);
        byte[] key = secretKey.getEncoded();
        String encode = Base64.encode(key);
        return encode;
    }


    public static String encrypt(String source, String key) {
        byte[] decodeKey = Base64.decode(key);
        String encrypt = null;
        try {
            byte[] iv = getSecureRandomIv(16);
            AES aes = new AES(Mode.CBC, Padding.PKCS5Padding, decodeKey, iv);
            encrypt = aes.encryptBase64(source);
            return encrypt.concat(new String(Hex.encodeHex(iv)));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return encrypt;
    }


    public static String decrypt(String source, String key) {

        byte[] decodeKey = Base64.decode(key);
        // 先分别解析密文值和iv值
        String message = source.substring(0, source.length() - 32);
        String iv = source.substring(source.length() - 32, source.length());
        byte[] decodeIv = HexUtil.decodeHex(iv);
        AES aes = new AES(Mode.CBC, Padding.PKCS5Padding, decodeKey, decodeIv);
        String decryptStr = aes.decryptStr(message);

        return decryptStr;


    }

    public static void main(String[] args) throws NoSuchAlgorithmException {
        String content = "test中文11111111111111111111111111111111111111111111111111111111111";
        String key = getSecureKeyStr(256);
        System.out.println("key:" + key);
        String encrypt = encrypt(content, key);
        System.out.println(encrypt);
        System.out.println(decrypt(encrypt,key));
    }
}
